<?php

/**
 * Created by PhpStorm.
 * User: 4399-0661
 * Date: 15-5-12
 * Time: 下午6:31
 */
class LibApplication
{

    static public function init()
    {
        $class = new self();
        $class->sqlAutoloadRegister();
        $class->regiestrShutdown();
    }

    private function regiestrShutdown()
    {
        register_shutdown_function(function () {
            $last_error = error_get_last();

            if (isset($last_error['type']) && $last_error['type'] == E_ERROR) {
                //\LibTools::redirect("/manager/index-500");
            }
        });
    }

    private function sqlAutoloadRegister()
    {
        spl_autoload_register(array($this, "_autoload"));
    }

    /**
     * autoload
     * @param $className
     * @return bool
     */
    private function _autoload($className)
    {
        if (stripos($className, "PHPExcel") !== false) {
            return false;
        }
        $className = str_replace("\\", DIRECTORY_SEPARATOR, $className);
        $nameArr = explode(DIRECTORY_SEPARATOR, $className);
        $cls = end($nameArr);
        $prefix = substr($cls, 0, 3);
        if ($prefix == "Lib" && count($nameArr) < 3) {
            $file = SYS_LIBRARY . DIRECTORY_SEPARATOR . $cls . ".php";
        } elseif(count($nameArr) > 3){
            $file = SYS_DIR . implode(DIRECTORY_SEPARATOR, $nameArr) . ".php";
        } else {
            $end = end($nameArr);
            unset($nameArr[count($nameArr) - 1]);
            if (preg_match('/^ctl(.*)/', $end)) {
                $nameArr[] = 'source';
            }
            if (preg_match('/^mdl(.*)/', $end)) {
                $nameArr[] = 'model';
            }
            $nameArr[] = $end;
            $file = SYS_DIR . implode(DIRECTORY_SEPARATOR, $nameArr) . ".php";
        }
        if (file_exists($file)) {
            include_once($file);
        } else {
            \LibLog::custom("FILE NOT EXISTS :" . $file);
        }
    }
} 